<?php

namespace App\Http\Controllers\Admin;


use App\Models\Supplier;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

use App\Models\Inventory;


class SupplierController extends Controller
{

    public function materialApproval(Request $request)
    {
        $fieldArr = $this->getFieldData();
        return view('admin.supplier.rk_index',['fieldArr'=>$fieldArr]);
    }

    public function materialApprovalData(Request $request)
    {
        $search = [];
        $search['yao_supplier_name'] = $request->yao_supplier_name?:'';
        $search['ytx_code'] = $request->ytx_code?:'';
        $search['date'] = $request->date?:'';

        $now_page=intval($request->input('page'));

        $per_page_num=intval($request->input('limit'));
        //偏移量
        $offset=($now_page-1)*$per_page_num;
        if($offset<0) $offset=0;

        $inventoryModel = new Inventory();
        $where = [];
        $res =  $inventoryModel->getRkTotalList($where,$search,$offset,$per_page_num);

        $data = ['code' => 0,'msg' => '正在请求中...','count' => $res['count'],'data' => $res['data']];
        return response()->json($data);
    }


    public function materialCheckIndex(Request $request)
    {

        return view('admin.supplier.rk_details_index');
    }

    public function detailsData(Request $request){


        $search = [];
        $search['product_code'] = $request->product_code?:'';
        $search['customer_name'] = $request->customer_name?:'';
        $search['date_time'] = $request->date?:'';

        $where = [];
        $now_page=intval($request->input('page'));
        $per_page_num=intval($request->input('limit'));
        //偏移量
        $offset=($now_page-1)*$per_page_num;
        if($offset<0) $offset=0;

        $inventoryModel = new Inventory();
        $where = [];

        $res = $inventoryModel->getDetailsDataList($where,$search,$offset,$per_page_num);
        $data = ['code' => 0,'msg' => '正在请求中...','count' => $res['count'],'data' => $res['data']];
        return response()->json($data);

    }

    public function generateData(Request $request)
    {
        // 根据当前日期生成前一个月的年月
        $now = date('Y-m-d');
        $previousMonth = date('Y-m', strtotime('-1 month', strtotime($now)));
        $inventoryModel = new Inventory();
        $where = ['start_time' => $previousMonth . '-01', 'end_time' => $previousMonth . '-31'];

        // 按条件删除 v_rk_total 表中的数据
        DB::table('v_rk_total')->where('data_time', $previousMonth)->delete();
        $results = $inventoryModel->getInventoryList($where);


        $amountStats = [];
        foreach ($results['data'] as $row) {
            $info = $inventoryModel->getSubjectFieldData(['ytx_code' => (int)$row['type_id']]);
            $supplierFieldData = $inventoryModel->getSupplierFieldData(['yao_supplier_code' => (int)$row['customer_code']]);
            if (!isset($info['kd_subject'])) {
                $info['kd_subject'] = 0;
            }
            if (!isset($supplierFieldData['jin_supplier_code'])) {
                $supplierFieldData['jin_supplier_code'] = 0;
                $supplierFieldData['jin_supplier_name'] = 0;
            }

            $customerId = $row['customer_code'] ?? '';
            $customer = $row['customer_name'] ?? '';
            $typeId = $row['type_id'] ?? 0; // 获取 type_id
            $taxFreeAmount = $row['tax_excluded_amount'] ?? 0;
            $taxAmount = $row['tax_amount'] ?? 0;
            $inclusiveAmount = $row['tax_included_amount'] ?? 0;

            // 累加各项金额
            $key = $customer . '_' . $info['kd_subject'];
            if (!isset($amountStats[$key])) {
                $amountStats[$key] = [
                    'customer_id' => $customerId,
                    'jin_supplier_code' => $supplierFieldData['jin_supplier_code'],
                    'jin_supplier_name' => $supplierFieldData['jin_supplier_name'],
                    'customer_name' => $customer,
                    'ytx_code' => $info['ytx_code'],
                    'ytx_subject' => $info['ytx_subject'],
                    'kd_code' => $info['kd_code'],
                    'kd_subject' => $info['kd_subject'],
                    'auxiliary_calculation' => $info['auxiliary_calculation'],
                    'total_tax_free_amount' => 0,
                    'total_tax_amount' => 0,
                    'total_inclusive_amount' => 0,

                ];
            }
            $amountStats[$key]['total_tax_free_amount'] += $taxFreeAmount;
            $amountStats[$key]['total_tax_amount'] += $taxAmount;
            $amountStats[$key]['total_inclusive_amount'] += $inclusiveAmount;
        }


        // 生成最终结果
        $finalResults = [];
        //生成8位随机数包含0-9和A-Z 函数生成
        $randomNumber = 'RK'.mt_rand(10000000, 99999999);
        foreach ($amountStats as $stats) {
            $finalResults[] = [
                'code'=>$randomNumber,
                'yao_supplier_code' => $stats['customer_id'],
                'yao_supplier_name' => $stats['customer_name'],
                'jin_supplier_code' => $stats['jin_supplier_code'],
                'jin_supplier_name' => $stats['jin_supplier_name'],

                'ytx_code' => $stats['ytx_code'],
                'ytx_subject' => $stats['ytx_subject'],
                'kd_code' => $stats['kd_code'],
                'kd_subject' => $stats['kd_subject'],
                'auxiliary_calculation' => $stats['auxiliary_calculation'],
                'tax_excluded_amount' => $stats['total_tax_free_amount'],
                'tax_amount' => $stats['total_tax_amount'],
                'tax_included_amount' => $stats['total_inclusive_amount'],
                'data_time'=>$previousMonth
            ];
        }
        // 批量插入数据
        if (!empty($finalResults)) {
            $res = DB::table('v_rk_total')->insert($finalResults);
        }
        if ($res){
            return response()->json(['code'=>0,'msg'=>'生成成功']);
        }else{
            return response()->json(['code'=>401,'msg'=>'生成失败']);
        }
    }


    /**
     * @param Request $request
     * @return void
     * 生成凭证
     */
    public function generateCertificate(Request $request)
    {

        $id = $request->get('id');
        if (!$id){
            return response()->json(['code'=>204,'msg'=>'参数错误']);
        }
        $inventoryModel = new Inventory();
        $info = $inventoryModel->getOneData('v_rk_total',['id'=>$id]);
        if (!$info){
            return response()->json(['code'=>204,'msg'=>'数据错误']);
        }

        //无税金额
        if($info['tax_excluded_amount']){
            $info['tax_excluded_amount'] = $info['tax_excluded_amount'];
            $info['abstract_excluded'] = $info['kd_subject'] . '暂估入库';
            $info['account_number_1'] = $info['kd_code'];

        }
        //税额
        if($info['tax_amount']){
            $info['amount'] = $info['tax_amount'];
            $info['account_number_2'] = '2221.17';
            $info['amount_abstract'] = '应交税额_待认证进项税额';

        }
        //含税金额
        if($info['tax_included_amount']){
            $info['tax_included_amount'] = $info['tax_included_amount'];
            $info['account_number_3'] = '2202.02.01';
            $info['included_abstract'] = '应付账款_暂估_物资';
            $info['asstActName2'] = $info['jin_supplier_name'];
            $info['asstActNumber2'] = $info['jin_supplier_code'];
            $info['asstActType2'] = '供应商';
            //
        }

        $certificateData = $inventoryModel->getStoredData($info);
        $url = 'http://8.152.0.162/eas/loginAndVoucher';
        $result = $this->KingdeePost($url, $certificateData);
        var_dump($result);die;
        if ($result === false) {
            return response()->json(['code' => 500, 'msg' => '调用金蝶接口失败']);
        }

        $decodedResult = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decodedResult)) {
            // JSON 解析失败或不是数组
            return response()->json(['code' => 500, 'msg' => '金蝶接口返回格式错误']);
        }

        // [0][4] 表示状态码，[0][6] 表示凭证编号
        if (!isset($decodedResult[0]) || !array_key_exists(4, $decodedResult[0])) {
            return response()->json(['code' => 500, 'msg' => '金蝶接口返回数据缺失']);
        }

        $status = $decodedResult[0][4];
        $jeCode = $decodedResult[0][6] ?? '';

        if ((string)$status === '0000') {
            $updateResult = DB::table('v_rk_total')
                ->where('id', $id)
                ->update([
                    'status' => 2,
                    'je_code' => $jeCode,
                    'updated_time' => date('Y-m-d H:i:s')
                ]);
            if (!$updateResult) {
                // 数据库更新失败
                return response()->json(['code' => 500, 'msg' => '数据库更新失败']);
            }
            return response()->json(['code' => 0, 'msg' => '生成凭证成功']);
        }

        return response()->json(['code' => 204, 'msg' => '生成凭证失败']);

    }


    public function generateEdit(Request $request)
    {
        $id = $request->get('id');
        $supplierModel = new Supplier();
        $data = $supplierModel->getfieldData('v_supplier_field',[]);

        return view('admin.supplier.rk_generate_index', ['data' => $data,'id'=>$id]);
    }


    public function generateSave(Request $request)
    {
        $id = $request->get('id');
        $jinSupplierCode = $request->get('jin_supplier_code');

        $data = [
            'jin_supplier_code' => $jinSupplierCode,
        ];

        $res = DB::table('v_rk_total')->where('id',$id)->update($data);
        if ($res){
            return response()->json(['code'=>0,'msg'=>'修改成功']);
        }else{
            return response()->json(['code'=>401,'msg'=>'修改失败']);
        }
    }


    public function generateSelect(Request $request)
    {
        $sql = "SELECT `kd_code`, MAX(`kd_subject`) AS `kd_subject` FROM `v_subject_field` GROUP BY `kd_code`;";
        $data = DB::select($sql);

        $finalResults = [];
        foreach ($data as $stats) {
            $finalResults[] = [
                'kd_code' => $stats->kd_code,
                'kd_subject' => $stats->kd_subject,
            ];
        }
        return view('admin.supplier.rk_select_index', ['data' => $finalResults]);
    }

    public function generateSubmit(Request $request)
    {
        $code = $request->get('jin_supplier_code');
        $dataTime = $request->get('date');

        $supplierModel = new Supplier();
        $field = $supplierModel->getOneBasicDictionaryData('v_subject_field',['kd_code'=>$code],['*']);
        $where =   [
            'kd_code' => $code,
            'data_time' => $dataTime,
        ];
        $data = $supplierModel->getRkTotalList($where);

        if (!$data){
            return response()->json(['code'=>204,'msg'=>'暂无数据']);
        }
        $tax_excluded_amount = 0;
        $tax_amount = 0;
        $tax_included_amount = 0;
        foreach ($data as $value){
            $tax_excluded_amount+=$value['tax_excluded_amount'];//无税金额
            $tax_amount += $value['tax_amount'];//税额
            $tax_included_amount += $value['tax_included_amount'];//含税金额
        }

        $info = [
            //无税金额
            'tax_excluded_amount' => $tax_excluded_amount,
            'abstract_excluded' => $field['kd_subject'] . '暂估入库',
            'account_number_1' => $code,
            //税额
            'tax_amount' => $tax_amount,
            'account_number_2' => '2221.17',
            'amount_abstract' => '应交税额_待认证进项税额',
            //含税金额
            'tax_included_amount' => $tax_included_amount,
            'account_number_3' => '2202.02.01',
            'included_abstract' => '应付账款_暂估_物资',
            'asstActType2' => '供应商',

        ];

        $inventoryModel = new Inventory();
        $certificateData = $inventoryModel->getStoredTotalData($info,$dataTime,$field,$data);

        $url = 'http://8.152.0.162/eas/loginAndVoucher';
        $result = $this->KingdeePost($url, $certificateData);

        if ($result === false) {
            return response()->json(['code' => 500, 'msg' => '调用金蝶接口失败']);
        }

        $decodedResult = json_decode($result, true);

        $status = $decodedResult[0][4];
        $jeCode = $decodedResult[0][6] ?? '';

        if ((string)$status === '0000') {
            return response()->json(['code' => 0, 'errmsg' => '提交成功']);
        }else{
            return response()->json(['code' => 400, 'errmsg' => $status]);
        }

    }
}
